const app = getApp()
import util from '../../../../utils/util'
import dateTimePicker from '../../../../utils/dateTimePicker'

import {
  GetIsseuHomes,
  UpVisitnew
} from '../../../../config/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    grider_storge: '',
    title:'',
    content:'',
    isShowPopup: false, // 选择家庭弹层是否显示
    allCheck: false, // 是否全选
    dateTimeArray: '',
    dateTime: '',
    start_time: '',
    endDate: '',
    home_list: [], // 家庭列表
    home_ids: '', // 所选家庭id
    home_name: '', // 所选家庭名称
    home_codeArrStr: '', // 家庭编号
    content: '', // 事件内容
    page: 1,
    limit: 20,
    search_name: '',
    imgs: [],
    count: 0,
    compressImgsSizeArr: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let grider_storge = wx.getStorageSync('grider')

    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var start_time = obj.dateTimeArray[0][obj.dateTime[0]] + '-' +
      obj.dateTimeArray[1][obj.dateTime[1]] + '-' +
      obj.dateTimeArray[2][obj.dateTime[2]] + ' ' +
      obj.dateTimeArray[3][obj.dateTime[3]] + ':' +
      obj.dateTimeArray[4][obj.dateTime[4]] + ':' +
      obj.dateTimeArray[5][obj.dateTime[5]];
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      start_time
    });

    this.setData({
      grider_storge
    })

    this.getHomeList() // 调用家庭列表
  },

  inputTitle(e) {
    this.setData({
      title: e.detail.value
    })
  },

  inputContent(e) {
    this.setData({
      content: e.detail.value
    })
  },

  changeDateTime(e) {
    this.setData({
      dateTime: e.detail.value
    });
    this.setData({
      start_time: this.data.dateTimeArray[0][this.data.dateTime[0]] + '-' + this.data.dateTimeArray[1][this.data.dateTime[1]] + '-' + this.data.dateTimeArray[2][this.data.dateTime[2]] + " " + this.data.dateTimeArray[3][this.data.dateTime[3]] + ':' + this.data.dateTimeArray[4][this.data.dateTime[4]] + ':' + this.data.dateTimeArray[5][this.data.dateTime[5]]
    })
    console.log("nihd", this.data.start_time);
  },

  changeDateTimeColumn(e) {
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    console.info("dateArr:", dateArr[2]);
    this.setData({
      dateTimeArray: dateArr
    });

    console.log("nihao", this.data.dateTimeArray)
  },

  getHomeList() { // 获取家庭列表
    let that = this;
    let params = {
      id: that.data.grider_storge.id,
      vollege_id: app.globalData.vollege_id,
      name: that.data.search_name,
      page: that.data.page,
      limit: that.data.limit
    }
    util.apiRequest(GetIsseuHomes, params, null).then(r => {
      console.log('家庭', r)
      var newList = that.data.home_list.concat(r.data.data)
      if (r.data.data.length == 0) {
        wx.showToast({
          title: '暂无更多',
          icon: 'none',
        })
      }
      that.setData({
        home_list: newList
      })
    })
  },

  scrolltolower(){
    let page = ++this.data.page
    this.setData({
      page
    })
    this.getHomeList();
  },

  searchNameInput(e) {
    console.log('搜素名称：', e.detail.value)
    let that = this;
    that.setData({
      page:1,
      search_name: e.detail.value,
      home_list:[]
    })
    this.getHomeList()
  },

  onSelectName() {
    this.setData({
      isShowPopup: true
    })
  },

  confirmName() { // 确定选择家庭
    this.setData({
      isShowPopup: false
    })
  },

  checkAll() { // 全选
    let that = this;
    let home_list = that.data.home_list;
    let idArr = []
    let nameArr = []
    let home_codeArr = []

    this.setData({
      allCheck: !this.data.allCheck
    })

    for (let i = 0; i < home_list.length; ++i) {
      if (this.data.allCheck) {
        home_list[i].isChecked = true
        idArr.push(home_list[i].id)
        nameArr.push(home_list[i].name)
        home_codeArr.push(home_list[i].code)
      } else {
        home_list[i].isChecked = false
      }
    }

    let idArrStr = idArr.toString()
    let nameArrStr = nameArr.toString()
    let home_codeArrStr = home_codeArr.toString();

    that.setData({
      home_ids: idArrStr,
      home_name: nameArrStr,
      home_codeArrStr,
      home_list
    })
  },

  checkboxChange(e) { // 选择
    console.log('选择家庭：', e)
    let namesString = e.detail.value.toString()
    const items = this.data.home_list
    const values = e.detail.value

    if (items.length == values.length) { // 选中/取消全选按钮
      this.setData({
        allCheck: true
      })
    } else {
      this.setData({
        allCheck: false
      })
    }

    let idArr = []
    let home_codeArr = []
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].isChecked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].name === values[j]) {
          idArr.push(items[i].id)
          home_codeArr.push(items[i].code)
          items[i].isChecked = true
        }
      }
    }
    let home_codeArrStr = home_codeArr.toString();
    let idArrStr = idArr.toString()

    this.setData({
      home_list: items,
      home_ids: idArrStr,
      home_name: namesString,
      home_codeArrStr
    })
  },

  formSubmit(){
    let params = {
      title: this.data.title,
      time: this.data.start_time,
      content: this.data.content,
      vollege_id: app.globalData.vollege_id,
      interview: this.data.home_ids,//走访家庭id
      interview_text: this.data.home_name,//走访家庭姓名
      grid_id: this.data.grider_storge.grid_id,
      visit_user: this.data.grider_storge.name,
      uid: this.data.grider_storge.id,
      imgs:this.data.imgs
    }
    util.apiRequest(UpVisitnew, params).then(r => {
      console.log('走访提交：', r)
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: r.data.info,
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/pages/grid/grid"
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: r.data.info,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 上传图片
  chooseImg: function(e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 800,
                maxHeight = 600;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function() {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.4,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              imgs: that.data.imgs
                            })
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },

  // 预览图片
  previewImg: function(e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  }
})